package com.boboPlanet.async;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author mis_wu
 * @date 2023/2/14 17:51
 * springboot整合线程池
 * 使用:异步执行的方法上 @Async("taskExecutor")
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    /**
     *   每秒需要多少个线程处理?
     *   tasks/(1/task cost)
     */
    private static final int corePoolSize = 10;

    /**
     * 线程池维护线程的最大数量
     * (max(tasks)- queueCapacity)/(1/task cost)
     */
    private static final int maxPoolSize = 30;

    /**
     * 缓存队列
     * (coreSizePool/task cost)*response time
     */
    private static final int queueCapacity = 10;

    /**
     * 允许的空闲时间 unit:s
     * 默认为60
     */
    private static final int keepAlive = 100;

    @Bean("gatewayTaskExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数  每秒需要多少个线程处理?  tasks/(1/task cost)
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置允许的空闲时间（秒）
        executor.setKeepAliveSeconds(keepAlive);
        // 设置默认线程名称
        executor.setThreadNamePrefix("thread-gateway-planet-");
        // 设置拒绝策略rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

}
